package com.lyh.hkcloud.module.m1300090;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.lyh.hkcloud.R;
import com.lyh.hkcloud.constants.BusinessConstants;
import com.lyh.hkcloud.constants.HttpUrlComstants;
import com.lyh.hkcloud.module.common.ActivityUtil;
import com.lyh.hkcloud.module.m1300085.service.Service;
import com.lyh.hkcloud.util.base.JsonUtil;
import com.lyh.hkcloud.util.base.LoadingUtils;
import com.lyh.hkcloud.util.base.SaveData;
import com.lyh.hkcloud.util.base.ToastUtils;
import com.lyh.hkcloud.util.http.listener.json.JsonFailuredListener;
import com.lyh.hkcloud.util.http.listener.json.JsonSuccessListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: wenwenliang
 * @description: 更新位置资产信息
 * @date: 2023-11-27 14:01
 **/
public class UpdateUsedActivity extends AppCompatActivity implements View.OnClickListener, View.OnFocusChangeListener {

    private Service service;
    private ImageView goBack;
    private Button btSave;
    private Button btCancel;
    private TextView tvCardNumber;
    private TextView tvInventoryNo;
    private EditText etUsed;

    /**
     * 当前实物码资产信息数据(每次打开页面查询)
     */
    private List<Map<String, Object>> faCardInfo = new ArrayList<>();

    /**
     * 姓名和工号：{"field_6887600017557688327":"03189","field_6887600017557688328":"xxxxx"}
     */
    Map<String, Object> usedMap = new HashMap<>();


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //加载布局
        setContentView(R.layout.activity_1300090_used);
        //调接口服务
        service = new Service(UpdateUsedActivity.this);
        //去除页头
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
        //初始化组件
        initAssembly();

    }

    @Override
    protected void onStart() {
        super.onStart();
        //赋值实物码
        Intent intent = getIntent();
        String cardNumber = intent.getStringExtra("cardNumber");
        String inventoryNo = intent.getStringExtra("inventoryNo");
        tvCardNumber.setText(cardNumber);
        tvInventoryNo.setText(inventoryNo);
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("psncode", cardNumber);
            jsonObject.put("facardcode", cardNumber);
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        //查询资产
        queryAssets(jsonObject);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_save:
                save();
                break;
            case R.id.go_back:
            case R.id.bt_cancel:
                finish();
                break;
        }

    }

    //组件初始化
    private void initAssembly() {
        btSave = findViewById(R.id.bt_save);
        btSave.setOnClickListener(this);
        btSave.setClickable(false);
        btCancel = findViewById(R.id.bt_cancel);
        btCancel.setOnClickListener(this);
        goBack = findViewById(R.id.go_back);
        goBack.setOnClickListener(this);
        tvCardNumber = findViewById(R.id.tv_card_number);
        tvInventoryNo = findViewById(R.id.tv_inventoryNo);
        etUsed = findViewById(R.id.et_used);
        etUsed.setOnFocusChangeListener(this);
    }


    /**
     * 保存数据
     */
    protected void save() {
        //禁用提交按钮
        etUsed.setEnabled(false);

        //组装参数
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject();
            List<String> facardidList = new ArrayList<>();
            List<Map<String, Object>> dataList = new ArrayList<>();


            for (Map<String, Object> val : faCardInfo) {
                Map<String, Object> stringObjectHashMap = new HashMap<>();
                facardidList.add(val.get("facardid") == null ? "" : val.get("facardid").toString());
                stringObjectHashMap.put("id", val.get("facardid") == null ? "" : val.get("facardid").toString());
                stringObjectHashMap.put("num", val.get("num") == null ? "" : val.get("num").toString());
                dataList.add(stringObjectHashMap);
            }

            jsonObject.put("dataIds", JsonUtil.toJSONArray(facardidList));
            jsonObject.put("data", JsonUtil.toJSONArray(dataList));
            jsonObject.put("maindata", JsonUtil.toJSONObject(usedMap));
            jsonObject.put("userid", SaveData.getString(this, "userid"));
            jsonObject.put("username", SaveData.getString(this, "userName"));

            Log.v("jsonObject资产信息提交", jsonObject.toString());

        } catch (JSONException e) {
            e.printStackTrace();
        }

        service.post(jsonObject, HttpUrlComstants.MODIFY_BINDING_RECIPIENT, new JsonSuccessListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {

                JSONObject jsonObject2 = new JSONObject();
                //盘点单号
                try {
                    String inventoryNo = tvInventoryNo.getText().toString();
                    String cardNumber = tvCardNumber.getText().toString();
                    jsonObject2.put("inventoryNo", inventoryNo);
                    jsonObject2.put("cardNumber", cardNumber);
                    //jsonObject2.put("def1", "");
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
                //同步资产信息
                service.post(jsonObject2, HttpUrlComstants.SYNC_FA_CARD, new JsonSuccessListener() {
                    @Override
                    public void onRespone(String msg, JSONObject response) {
                        String code = response.optString("code");
                        if ("0000".equals(code)) {
                            //
                            Toast.makeText(UpdateUsedActivity.this,response.optString("message"),Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent(UpdateUsedActivity.this, IndexActivity.class);
                            setResult(11, intent);
                            //退出当前页面
                            finish();
                        }
                    }
                }, new JsonFailuredListener() {
                    @Override
                    public void onRespone(String msg, JSONObject response) {
                        Log.e("error", response.optString("message"));
                        Toast.makeText(UpdateUsedActivity.this,"资产同步盘点系统出现异常，请联系开发人员",Toast.LENGTH_SHORT).show();
                        btSave.setEnabled(true);
                    }
                });

            }
        }, new JsonFailuredListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                Log.e("error", response.optString("message"));
                LoadingUtils.getInstance(UpdateUsedActivity.this).hide();
                btSave.setEnabled(true);
            }
        });

    }

    //焦点
    @Override //b 焦点中:true   失去焦点：false
    public void onFocusChange(View view, boolean b) {
        //1、焦点后的处理：判定是否清空信息
        String used = etUsed.getText().toString();

        if (b) {
            etUsed.setText("");
            btSave.setClickable(false);
            btSave.setTextColor(Color.parseColor("#000000"));
        }

        //2、失去焦点后的处理：工号查询并赋值
        if (!b) {

            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("psncode", used);
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
            //查询系统中是否有当前的工号:有赋值，没有则清空
            queryPersonnelInformation(jsonObject);
        }
    }

    //时间分发方法重写
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        //如果是点击事件，获取点击的view，并判断是否要收起键盘
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            //获取目前得到焦点的view
            View v = getCurrentFocus();
            //判断是否要收起并进行处理
            if (ActivityUtil.isShouldHideKeyboard(v, ev)) {
                ActivityUtil.hideKeyboard(v.getWindowToken(), this, etUsed);
            }
        }
        //这个是activity的事件分发，一定要有，不然就不会有任何的点击事件了
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 通过工号，查询人员信息
     *
     * @param jsonObject {"psncode":"03184"}
     * @Date 2023/11/29 17:47
     **/
    public void queryPersonnelInformation(JSONObject jsonObject) {
        service.post(jsonObject, HttpUrlComstants.QUERY_PERSONNEL_DETAILS, new JsonSuccessListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                JSONArray data = response.optJSONArray("data");

                try {
                    JSONObject jsonObject2 = new JSONObject(data.get(0).toString());
                    JSONArray facardinfo = jsonObject2.optJSONArray("psninfo");

                    if (facardinfo == null || facardinfo.length() == 0) {
                        Toast.makeText(UpdateUsedActivity.this, "查询人员信息为空", Toast.LENGTH_SHORT).show();
                        etUsed.setText("系统中无此工号");
                        btSave.setClickable(false);
                        btSave.setTextColor(Color.parseColor("#000000"));
                        return;
                    }
                    JSONObject usedInfo = new JSONObject(facardinfo.get(0).toString());
                    if (usedInfo == null) {
                        Toast.makeText(UpdateUsedActivity.this, "查询人员信息为空", Toast.LENGTH_SHORT).show();
                        etUsed.setText("系统中无此工号");
                        btSave.setClickable(false);
                        btSave.setTextColor(Color.parseColor("#000000"));
                        return;
                    }
                    String psncode = usedInfo.getString("psncode");
                    String psnname = usedInfo.getString("psnname");
                    etUsed.setText(psncode + "-" + psnname);
                    //使用人代码
                    usedMap.put("field_6887600017557688327", psncode == null ? "" : psncode);
                    //使用人名称
                    usedMap.put("field_6887600017557688328",psnname == null ? "" : psnname);
                    //释放保存按钮
                    btSave.setClickable(true);
                    btSave.setTextColor(Color.parseColor("#0000CD"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new JsonFailuredListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                Log.e("error", response.optString("message"));
                etUsed.setText("查询出现异常,请稍后重试");
                ToastUtils.makeText(UpdateUsedActivity.this, msg, ToastUtils.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 查询资产
     */
    private void queryAssets(JSONObject jsonObject) {
        service.post(jsonObject, HttpUrlComstants.QUERY_ASSET_DETAILS, new JsonSuccessListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {


                JSONObject jsonObject3 = null;
                try {
                    jsonObject3 = JsonUtil.getJsonObject(response, "facardinfo", UpdateUsedActivity.this);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (jsonObject3 == null) {
                    return;
                }

                Map<String, Object> map = new HashMap<>();

                map.put("facardcode", jsonObject3.optString("facardcode") == null ? "" : jsonObject3.optString("facardcode").toString());
                map.put("maname", jsonObject3.optString("maname") == null ? "" : jsonObject3.optString("maname").toString());
                map.put("manumber", jsonObject3.optString("manumber") == null ? "" : jsonObject3.optString("manumber").toString());
                map.put("facardid", jsonObject3.optString("facardid") == null ? "" : jsonObject3.optString("facardid"));
                map.put("num", jsonObject3.optString("num") == null ? 0 : jsonObject3.optString("num"));
                faCardInfo.add(map);
            }

        }, new JsonFailuredListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                Log.e("error", response.optString("message"));
            }
        });
    }
}
